// 这是首页的接口请求
import express, { json } from 'express';
import sql from '../mysqlOption/Sql'
import uuID from 'node-uuid'
import { MyCURD } from '../my/CURDMySQL';
const router = express.Router();
// 轮播图数据格式
interface Lunbotu{
    id:number,
    iconlocation:string,
    iconlink:string,
    code:string,
    commonts:string,
    title:string,
    local?:string
}
// icon数据格式
interface IconData{
    id:number,
    iconlocation:string,
    local?:string,
    comment:string | null,
    title:string | null,
    code :string
}
// mimiswiper数据格式
interface MiniSwiper{
    id:number,
    iconlocation:string,//网络位置
    local?:string,//本地位置
    title:string | null, 
    code :string
}
// 商品列表接口
interface ProductList{
    id:number,
    productId:string,
    name:string,
    nowPrice:string,
    afterPrice:string,
    productDescribe:string,
    location:string,
    local?:string
}
router.get("/api/lunbo",(req,res)=>{
    // console.log("访问了轮播图数据")
    sql.query("select * from lunbotu",(err,result)=>{
        if(err) {
            console.log(err)
            return new Error("数据库查询失败");
        }else{
            // console.log(result);
            // 把本地路径过滤
            result.forEach( (item:Lunbotu)=> {
                delete item.local;
            });
            res.send({
                success:"轮播图访问成功",
                data:result
            })
        }
    })
}
)
//点选模块的内容 icon
router.get("/api/icon",(req,res)=>{
    sql.query("select * from icon",(err,result)=>{
        if(err){
            console.log('查询icon表出错');
            console.log(err)
            return res.send({
                msg:"请求icon数据出错",
                code :400
            })
        }
        result.forEach((item:IconData) => {
                delete item.local;
        });
        res.send({
            success:"点选内容访问成功",
            code:200,
            data:result
        })
    })
    
})
// 商品挑选模块
router.get("/api/product",(req,res)=>{
    console.log(uuID.v1());
    res.send({
        success:"商品挑选模块访问成功"
    })
})

router.get("/api/miniswiper",(req,res)=>{
    sql.query("select * from miniswiper",(err,result)=>{
        if(err){
            console.log(err)
            return res.send({
                msg:"查询miniswiper失败",
                code :400,
            })
        }
        result.forEach((item:MiniSwiper)=> {
            delete item.local;
        });

        res.send({
            msg:"请求miniswiper数据成功",
            success : true,
            code :200,
            data:result
        })
    })
})
// 商品列表
router.get("/api/productList/:pageNum",async (req,res)=>{
    // console.log(req.params)
    let page = req.params.pageNum;
    const sentence = 'select * from productinfo id > ()'
    const data = await MyCURD("select * from productinfo where id > (?*5) limit 5",[page])
    res.send({
        data
    })
   
})
// 单个商品的详细信息
// 接口返回的信息结构
interface ProductDetail{
    id:number,
    product_id:string,
    picture_local?:string,
    picture_net:string,
}
router.get("/api/productDetail",async (req,res)=>{
    const {id} = req.query;
    if(id === '' || id === undefined){
        return res.send({
            msg:"ID不能为空"
        })
    }
    const sql_icon = "select * from productarray where product_id = ?"
    const sql_text = "select id,productid,name,productdescribe,nowprice,beforeprice from productinfo where productid = ?"
    const data_icon = await MyCURD(sql_icon,[id as string])
    const data_text = await MyCURD(sql_text,[id as string])
    // console.log(data_text)
    data_icon.forEach((item:ProductDetail) => {
        delete item.picture_local
    });
    res.send({
        data:{
            data_icon,
            data_text
        }
    })
})
// 通过get传递过来的数据
interface GetData{
    id:string,
    count : number,
    check:boolean
}
// MySQL返回的数据
interface GetproductInfo{
    productid:string,
    name:string,
    nowprice:number,
    picture:string,
    count ? : number
}
router.get("/api/getproductinfo",async (req,res)=>{
    const info:GetData[] = JSON.parse(req.query.idobj as string);
    // console.log(info)
    const client = [];
    // let price = 0;
    for(let i = 0 ;i < info.length;i++){
    const result:GetproductInfo[] = await MyCURD("select productid,name,nowprice,picture from productinfo where productid=?",[info[i].id]);
    result[0].count = info[i].count;//把传过来的数量添加到搜索结果
    // if(info[i].check == true){
    //     price +=  (result[0].nowprice * info[i].count)
    // }
    client.push(result[0]);
    }
    
    res.send({
        msg:"success",
        resultData : client
    })
})
// 商品勾选的信息
interface ProductCheck{
    id:string,
    count:number,
    check:boolean
}
interface GetPriceResult{
    productid:string,
    nowprice:number,
    name:string,
    count ? :number
}
router.get("/api/getprice",async (req,res)=>{
    // 检查一共有多少个商品被check了，如果被check的商品大于一个就用查询的字符串相加more
    let language = "select  productid,nowprice,name from productinfo where productid = ? "
    const {productOBJ} = req.query;
    const productCheck:ProductCheck[] = JSON.parse(productOBJ as string);
    let totalPrice:number = 0;
    // 先判断是否被勾选
    console.log(productCheck)
    console.log("长度是：",productCheck.length)
    // const product_arr:string[] = [];//这是一个用来查询价格的数组(产品id)
    // 筛查出所有勾选的商品
    // for(let i = 0; i < productCheck.length ; i++){
    //       if(productCheck[i].check === true){
    //         product_arr.push(productCheck[i].id)
    //       }
    // }
    // 查询商品的价格
    let result:GetPriceResult[] = [];
    // 当勾选的商品数量不等于0的时候
    // if(product_arr.length > 0){
    //      result =  await MyCURD(language,product_arr);
    // }
    const totalResult = [];
    for(let i = 0;i < productCheck.length;i++){
        if(productCheck[i].check === true){
            result = await MyCURD(language,[productCheck[i].id])
            result[0].count = productCheck[i].count;
            totalResult.push(result[0]);
        }
    }
    // console.log(totalResult)
    for(let i = 0 ; i < totalResult.length; i++){
        totalPrice += totalResult[i].count! * totalResult[i].nowprice;
    }
    // console.log(totalPrice);
    res.send({
        msg:"success",
        totalPrice
    })
})


router.get("/api/productinfosingle",async (req,res)=>{
    const id = req.query.id as string;
    const result = await MyCURD("select nowprice,picture,name from productinfo where productid = ?",[id]);
    res.send({
        msg:"测试接口",
        data : result[0]
    })
})
export default router;